package com.tangqiao;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.Calendar;

public class Loginer {
	
	public static String getTime() {
		Calendar date = Calendar.getInstance();
		return "["+date.get(Calendar.YEAR)+"-"+(date.get(Calendar.MONTH)+1) +"-"+ date.get(Calendar.DATE) + " "+ date.get(Calendar.HOUR_OF_DAY)+ ":" + date.get(Calendar.MINUTE)+":"+ date.get(Calendar.SECOND)+"] ";
	}

	private static DatagramSocket socket;
	static {
		try {
			socket = new DatagramSocket();
		} catch (SocketException e) {
			e.printStackTrace();
		}
		;
	}

	private static String doLogin(String info) {
		boolean error = false;
		String ret = null;
		String postinfo = info;
		System.out.println(getTime() + "INFO: " + postinfo);
		try {
			Socket s = new Socket(InetAddress.getByName("172.16.202.201"), 3333);
			InputStream ins = s.getInputStream();
			OutputStream ous = s.getOutputStream();
			String sj;
			sj = "POST /cgi-bin/do_login HTTP/1.1" + "\r\n"
					+ "Content-Type: application/x-www-form-urlencoded"
					+ "\r\n" + "User-Agent: my session" + "\r\n"
					+ "Host: 172.16.202.201:3333" + "\r\n";
			sj += "Content-Length: " + postinfo.length() + "\r\n";
			sj += "Cache-Control: no-cache" + "\r\n";
			sj += "" + "\r\n";

			sj += postinfo;
			byte[] b1 = sj.getBytes();
			ous.write(b1);

			BufferedReader br = new BufferedReader(new InputStreamReader(ins));
			while (true) {
				String line = br.readLine();
				if (line == null)
					break;
				// System.out.println(line);
				if (line.indexOf(',') != -1) ret = line;
				else if (line.indexOf("password")!= -1) {
					ret = line;
					error = true;
				}
			}
			br.close();
			ous.close();
			s.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (error) return ret;
		return ret.substring(0, ret.indexOf(','));
	}

	public static void main(String[] args) {
		if (args.length != 3) {
			System.out
					.println("Usage: com.tangqiao.Loginer username password mac_address");
			return;
		}
		String username = args[0];
		String password = args[1];
		String macAddr = args[2];
		username = "0711210013";
		macAddr = "00-16-D3-96-F6-1A";

		String time = TimeGetter.getTime();
		System.out.println(getTime() + "INFO: time = " + time);

		password = BNUEncoder.encode(password, time);
		macAddr = BNUEncoder.encode(macAddr, time);

		String postInfo = "username=" + username + "&password=" + password
				+ "&drop=0&type=2&n=11" + "&mac=" + macAddr;

		String uid = Loginer.doLogin(postInfo);
		if (uid.indexOf("password") != -1) {
			System.out.println("getTime() + ERROR: " + uid);
			return ;
		}
		Long id = Long.parseLong(uid);
		byte[] bytes = longToByteArray1(id);
		
		System.out.println(getTime() + "INFO: uid = " + uid);
		while (true) {
			try {
				Thread.sleep(1000 * 60 * 3);
				Loginer.keepAlive(bytes);
				System.out.println(getTime() + "INFO: Keep Alive.");
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (SocketException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private static void keepAlive(byte[] bytes) throws IOException {
		DatagramPacket packet = new DatagramPacket(bytes, bytes.length,
				InetAddress.getByName("172.16.202.201"), 3335);
		socket.send(packet);
	}

	public static byte[] longToByteArray1(long a) {
		byte[] result = new byte[8];
		for (int i = 0; i < 8; ++i) {
			result[i] = (byte)(a & 0xFF);
			a = a >> 8;
		}
		return result;
	}
}
